<template>
  <div class="warpper">
    <div class="toolbar">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" label-width="100px" label-position="right">

        <el-form-item label="Name">
          <el-input v-model="searchForm.name" @keyup.enter.native="search" placeholder="Enter Name"
            style="width: 250px;">
          </el-input>
        </el-form-item>

        <el-form-item label="SKU">
          <el-input v-model="searchForm.sku" placeholder="Enter SKU" style="width: 250px;">
          </el-input>
        </el-form-item>

        <el-form-item label="Category" prop="category_id" style="width: 360px;">
          <treeselect v-model="searchForm.category_id" :options="deptOptions" :normalizer="normalizer"
            placeholder="Select Category" style="width: 250px;" @open="onOpen" @close="onClose" />
        </el-form-item>

        <el-form-item>
          <el-button @click="find()" plain style="margin-left: 24px;">Search</el-button>
          <el-button type="primary" v-permission="['products.store']" plain @click="productadd()">+ New</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table">
      <el-table @sort-change="handleSortChange" :data="tableData" size="small" stripe border style="width: 100%">

        <el-table-column type="selection" width="50" align="center" />

        <el-table-column prop="name" label="Name" width="160" align="center" sortable="name" >
          <template v-slot="scope">
            <el-link type="primary" :underline="false" @click="edit(scope.row.id)">{{ scope.row.name }}</el-link>
          </template>
        </el-table-column>

        <el-table-column prop="sku" label="SKU" width="100" align="center" sortable="sku" >
          <template v-slot="scope">
            <span>{{ scope.row.sku }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="uom" label="Spec" width="100" align="center" sortable="uom" >
          <template v-slot="scope">
            <span>{{ scope.row.uom }}{{ scope.row.uom_sku }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="category_name" label="Category" min-width="120" align="center" sortable="category_name" >
          <template v-slot="scope">
            <span>{{ scope.row.category_name }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="packaging" label="Packaging" width="110" sortable="packaging"  />

        <el-table-column prop="brand_name" label="Brand" width="100" align="center" sortable="brand_name" >
          <template v-slot="scope">
            <span>{{ scope.row.brand_name }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="price" label="Price(S$)" width="100" sortable="price"  />

        <el-table-column prop="rop" label="ROP Point" width="110" sortable="rop"  />

        <el-table-column prop="quantity" label="Pre Stock Quantity" width="160">
          <template v-slot="scope">
            <div v-if="scope.row.prestock>0">
              <el-tooltip placement="top">
                <div slot="content" v-for="(stock, index) in scope.row.prestocklist" :key="index" class="stock-item">
                  <span class="name" style="margin-right: 20px; ">{{ stock.name }}</span>
                  <span class="quantity">{{ stock.quantity }}</span>
                  <br>
                </div>
                <el-link type="prestock" :underline="false"
                  style="text-decoration: underline;">{{scope.row.prestock}}</el-link>
              </el-tooltip>
            </div>
            <span v-else>0</span>
          </template>
        </el-table-column>

        <el-table-column prop="quantity" label="Stock Quantity" width="130" sortable>
          <template v-slot="scope">
            <div v-if="scope.row.stock>0">
              <el-tooltip placement="top">
                <div slot="content" v-for="(stock, index) in scope.row.stocklist" :key="index" class="stock-item">
                  <span class="name" style="margin-right: 20px; ">{{ stock.name }}</span>
                  <span class="quantity">{{ stock.quantity }}</span>
                  <br>
                </div>
                <el-link type="stock" :underline="false"
                  style="text-decoration: underline;">{{scope.row.stock}}</el-link>
              </el-tooltip>
            </div>
            <span v-else>0</span>
          </template>
        </el-table-column>


        <el-table-column prop="stock" label="Status" width="100" sortable="stock">
          <template v-slot="scope">
            <span :class="getStatusColor('Normal')"
              style="width: 90px;height: 20px;overflow: hidden;display: inline-block;" v-if="scope.row.stock>0">In
              stock</span>
            <span :class="getStatusColor('Hidden')" v-else>Sold Out</span>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="Created Time" sortable min-width="120">
          <template v-slot="scope">
            <span>{{ scope.row.created_at | showDateTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="Actions" width="240">
          <template slot-scope="scope">
            <el-button plain v-permission="['products.show']" @click="copy(scope.row)" size="mini">copy</el-button>
            <el-button plain v-permission="['products.show']" @click="edit(scope.row.id)" size="mini">edit</el-button>
            <el-button plain v-permission="['products.destroy']" type="danger" size="mini"
              @click="del(scope.row.id)">delete</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page">
      <el-pagination v-if="isPaginate" background :current-page="page.current_page" :page-sizes="page.sizes"
        :page-size="page.per_page" layout="prev, pager, next" :total="page.total" @size-change="sizeChange"
        @current-change="currentChange" />
    </div>


    <div class="form">
      <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false"
        customClass="customWidth">
        <el-form v-if="dialogFormVisible" ref="ruleForm" :model="formData" :rules="rules" label-width="160px"
          style="width:85%">
          <el-row :gutter="20">
            <el-col :span="11">
              <el-form-item label="Name" prop="title" style="width:460px">
                <el-input v-model="formData.name" autocomplete="off" placeholder="Name" />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="Favorite Suppliers" prop="suppliers">
                <el-select v-model="formData.suppliersdata" placeholder="Select Favorite Suppliers" multiple
                  multiple-limit="3" style="width:300px">
                  <el-option v-for="item in suppliers" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>

              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="Categorys" prop="category_id">
            <treeselect v-model="formData.category_id" :options="deptOptions" :normalizer="normalizer"
              placeholder="Select Category" style="width: 300px;" />
          </el-form-item>

          <el-form-item label="SKU" prop="sku" style="width: 460px;">
            <el-input v-model="formData.sku" placeholder="SKU"></el-input>
          </el-form-item>

          <el-form-item label="Price(S$)" prop="price">
            <el-input-number v-model="formData.price" :min="1" label="Price(S$)" style="width:300px"></el-input-number>
          </el-form-item>

          <el-form-item label="Packaging" prop="packaging">
            <el-select v-model="formData.packaging" placeholder="Choose Packaging" style="width:300px">
              <el-option v-for="item in packaging" :key="item.id" :label="item.name" :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="UOM" prop="uom">
            <el-input-number v-model="formData.uom" :min="0"></el-input-number>
            <el-select v-model="formData.uom_sku" placeholder="Choose Uom" style="width: 115px;">
              <el-option v-for="item in uom_sku" :key="item.id" :label="item.name" :value="item.name"
                style="width: 115px;">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="ROP Point" prop="rop">
            <el-input-number v-model="formData.rop" :min="1" style="width:300px"> </el-input-number>
          </el-form-item>

          <el-form-item label="Status" prop="status">
            <el-select v-model="formData.status" placeholder="Choose status" style="width:300px">
              <el-option v-for="item in status" :key="item.id" :label="item.name" :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="Brand" prop="brand_id">
            <el-select v-model="formData.brand_id" placeholder="Choose brand" style="width:300px">
              <el-option v-for="item in brand" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="image" style="margin-bottom: 0px;" prop="image">
            <el-upload ref="uploadAvatar" class="avatar-uploader" action="#" :show-file-list="false"
              :on-change="changeAvatar" :auto-upload="false" :http-request="avatarUpload" name="file">
              <img v-if="formData.image" :src="formData.image" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>






          <el-form-item label="Remark" prop="remark" style="width: 460px;">
            <el-input v-model="formData.remark" placeholder="Remark001"></el-input>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="saveHandle('ruleForm')">Submit</el-button>
          <el-button @click="dialogFormVisible = false">Cancel</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import CURD from "@/mixin/CURD";
  import {
    store as uploadImg
  } from "@/api/medias";
  import Tinymce from "@/components/Tinymce";
  import {
    update
  } from "@/api/product";
  import {
    index
  } from "@/api/product_category";
  import {
    index as superindex
  } from "@/api/supplier";
  export default {
    name: "productIndex",
    mixins: [CURD],
    components: {
      Tinymce,
      Treeselect
    },
    data() {
      return {
        formData: {},
        brand: [],
        status: [{
          id: 1,
          name: "Normal",
        }, {
          id: 2,
          name: "Hidden",
        }],
        uom_sku: [{
          id: 1,
          name: "KG",
        }, {
          id: 2,
          name: "G",
        }, {
          id: 3,
          name: "ML",
        }, {
          id: 4,
          name: "L",
        }],
        suppliers: [],
        packaging: [{
          id: 1,
          name: "Bottle",
        }, {
          id: 2,
          name: "Pail",
        }, {
          id: 3,
          name: "Bag",
        }, {
          id: 4,
          name: "Packet",
        }],
        module: "product",
        newTitle: "New products",
        editTitle: "Edit product",
        isPaginate: true,
        isUploadFile: false,
        fileReader: new FileReader(),
        isShow: false,
        imageUrl: "",
        categories: [],
        deptOptions: [],
        searchForm: {

        },

      };
    },
    async created() {
      const {
        data
      } = await superindex(1, 100); // 假设index是一个异步函数
      console.log(data, "ssss")
      this.suppliers = data;
      try {
        const {
          data
        } = await index(1, 100); // 假设index是一个异步函数
        this.categories = data;
        // 调用handleTree方法处理数据
        this.deptOptions = this.handleTree(data, "id", "parent_id");
      } catch (error) {
        console.error('Failed to fetch categories:', error);
      }
    },
    methods: {
        handleSortChange({ column, prop, order }) {
        this.searchForm.sort_field = prop;
        this.searchForm.sort_order = order === 'ascending' ? 'asc' : 'desc';
        this.fetchData();
      },
      async fetchData() {
        let { index } = require(`@/api/${this.module}`);
        const res = await index(
          this.page.current_page,
          this.page.per_page,
          this.searchForm  // 包含了排序参数
        );
        if (
          res.data instanceof Object &&
          typeof this.transfromData === "function"
        ) {
          let data = this.transfromData(res.data);
          this.tableData = data;
        } else {
          this.tableData = res.data;
        }
        if (res.meta) {
          // 分页
          res.meta.per_page = parseInt(res.meta.per_page);
          this.page = Object.assign(this.page, res.meta);
        } else {
          this.isPaginate = false; // 不分页
        }
      },
      productadd() {
        this.$router.push({
          path: '/product/productadd',
          query: {
            id: null
          }
        })
      },
      copy(row) {
        row.name = row.name + "01"
        row.sku = row.sku + "01"
        this.copyadd(row)
      },
      edit(id) {
        this.$router.push({
          path: '/product/editproduct',
          query: {
            id: id
          }
        })
      },
      // async edit(id) {
      //   let {
      //     show
      //   } = require(`@/api/${this.module}`);
      //   let {
      //     data
      //   } = await show(id);
      //   var isbbb = [];
      //   var issp = data.suppliers;
      //   issp = issp.split(",");
      //   for (let is = 0; is < issp.length; is++) {
      //     isbbb.push(parseInt(issp[is]));
      //   }
      //   data.suppliersdata = isbbb;
      //   this.formData = data;
      //   this.isNew = false;
      //   this.isEdit = true;
      //   this.setTitle();
      //   this.dialogFormVisible = true;
      // },
      onOpen(id) { // 展开
        this.currentOpen = id;
      },
      onClose(id) { // 关闭
        if (this.currentOpen === id) {
          this.currentOpen = null;
        }
      },
      getStatusColor(zt) { // 状态颜色
        if (zt === 'Normal') {
          return 'green-text';
        } else if (zt === 'Hidden') {
          return 'red-text';
        } else {
          return 'green-text';
        }
      },
      normalizer(node) {
        if (node.children && node.children.length === 0) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children
        };
      },
      handleTree(data, id, parentId, children) {
        let config = {
          id: id || 'id',
          parentId: parentId || 'parentId',
          childrenList: children || 'children'
        };

        var childrenListMap = {};
        var nodeIds = {};
        var tree = [];

        for (let d of data) {
          let parentId = d[config.parentId];
          if (childrenListMap[parentId] == null) {
            childrenListMap[parentId] = [];
          }
          nodeIds[d[config.id]] = d;
          childrenListMap[parentId].push(d);
        }

        for (let d of data) {
          let parentId = d[config.parentId];
          if (nodeIds[parentId] == null) {
            tree.push(d);
          }
        }

        for (let t of tree) {
          adaptToChildrenList(t);
        }

        function adaptToChildrenList(o) {
          if (childrenListMap[o[config.id]] !== null) {
            o[config.childrenList] = childrenListMap[o[config.id]];
          }
          if (o[config.childrenList]) {
            for (let c of o[config.childrenList]) {
              adaptToChildrenList(c);
            }
          }
        }
        return tree;
      },
      adjustOrder(row) {
        row.isEdit = true;
      },
      async saveOrder(row) {
        let data = {
          id: row.id,
          order: row.order,
          action: "order"
        };
        row.isEdit = false;
        let {
          info
        } = await update(data);
        this.fetchData();
      },
      transfromData(data) {
        let result = data.map((item) => {
          item.isEdit = false;
          return item;
        });
        return result;
      },
      saveHandle(form) {
        this.$refs[form].validate(async (valid) => {
          if (valid) {
            if (this.isUploadFile) {
              // 更改了图片，则必须先传图片
              this.$refs.uploadAvatar.submit();
            } else {
              this.save(form);
            }
          } else {
            this.$message.error("Data filling error, please fill in again according to the requirements");
          }
        });
      },
      async copyadd(row) {
        try {
          let {
            store
          } = require(`@/api/${this.module}`);
          let {
            info
          } = await store(row);
          this.$message.success("Save successfully");
          this.fetchData();
          this.isEdit = false;
          this.isNew = false;
          this.dialogFormVisible = false;
        } catch (error) {
          let result = error.response.data;
          this.$message.error(result.info);
        }

      },
      async save(form) {
        this.$refs[form].validate(async (valid) => {
          if (valid) {
            try {
              this.formData.suppliers = this.formData.suppliersdata.toString();
              if (this.isEdit) {
                let {
                  update
                } = require(`@/api/${this.module}`);
                let {
                  info
                } = await update(this.formData);
                this.$message.success("Edit successfully");
              }
              if (this.isNew) {
                let {
                  store
                } = require(`@/api/${this.module}`);

                let {
                  info
                } = await store(this.formData);
                this.$message.success("Save successfully");
              }
              this.fetchData();
              this.isEdit = false;
              this.isNew = false;
              this.dialogFormVisible = false;
            } catch (error) {
              let result = error.response.data;
              this.$message.error(result.info);
            }
          } else {
            this.$message.error("Data verification error, please input according to the specified rules");
            return false;
          }
        });
      },
      async avatarUpload(options) {
        const file = options.file;
        if (file) {
          this.fileReader.readAsDataURL(file);
        }
        this.fileReader.onload = async () => {
          const formData = new FormData();
          formData.append("file", file);
          uploadImg(formData)
            .then((res) => {
              const {
                data
              } = res;
              this.formData.image = data.url;
              this.save("ruleForm");
            })
            .catch((err) => {
              options.onError(err);
            });
        };
      },
      changeAvatar(file, fileList) {
        const reader = new window.FileReader();
        reader.readAsDataURL(new Blob([file.raw]));
        reader.onload = (e) => {
          this.formData.image = reader.result;
          this.imageUrl = reader.result;
          this.isUploadFile = true;
        };
      },
      async changeStatus(row) {
        let tips = "";
        if (row.status) {
          tips = "是否启用该文章?";
        } else {
          tips = "是否禁用该文章?";
        }
        this.$confirm(tips, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(async () => {
            let data = {
              id: row.id,
              status: row.status,
              action: "status"
            };
            let {
              info
            } = await update(data);
            this.$message.success(info);
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "Cancelled deletion"
            });
          });
      }
    }
  }
</script>
<style>
  .customWidth {
    width: 80%;
  }
</style>
<style>
  .table,
  .toolbar,
  .page {
    margin: 20px;
  }

  .toolbar {
    margin-top: 10px;
    padding: 5px;
  }

  .table {
    margin-bottom: 10px;
  }

  .page {
    margin-top: 10px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 78px;
    height: 78px;
    line-height: 78px;
    text-align: center;
  }

  .green-text {
    color: green;
  }

  .red-text {
    color: red;
  }

  .yellow-text {
    color: yellow;
  }
</style>